package com.donger.business.upms.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.donger.business.upms.entity.SysPermission;
import com.donger.business.upms.entity.SysRole;
import com.donger.business.upms.query.RoleQuery;
import com.donger.business.upms.service.ISysPermissionService;
import com.donger.business.upms.service.ISysRoleService;
import com.donger.common.core.exception.BizException;
import com.donger.common.core.utils.Res;
import com.donger.common.core.utils.Result;
import com.donger.common.data.entity.DropDown;
import com.donger.common.query.utils.QueryGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色 前端控制器
 * </p>
 *
 * @author xyx
 * @since 2019-01-12
 */
@AllArgsConstructor
@RestController
@RequestMapping("/sys/role")
@Api(value = "/sys/role", tags = "角色部分开放API")
public class SysRoleController {

    private static final String MODULE_NAME = "系统角色管理";

    private final ISysRoleService sysRoleService;

    private final ISysPermissionService sysPermissionService;

    /**
     * 角色列表
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询角色信息")
    public Result<IPage<SysRole>> page(Page<SysRole> page, RoleQuery roleQuery) {
        QueryWrapper<SysRole> sysRoleQueryWrapper = QueryGenerator.initQueryWrapper(roleQuery);
        return Res.ok(sysRoleService.page(page, sysRoleQueryWrapper));
    }

    @GetMapping("/list")
    @ApiOperation(value = "角色信息列表")
    public Result list(SysRole sysRole) {
        return Res.ok(sysRoleService.list(Wrappers.query(sysRole)));
    }


    /**
     * 角色下拉框
     */
    @GetMapping("/dropdown")
    @ApiOperation(value = "角色信息下拉")
    public Result<List<DropDown>> select() {
        List<DropDown> list = sysRoleService.list().stream()
                .map(item -> new DropDown().setLabel(item.getRoleName()).setValue(item.getRoleId()))
                .collect(Collectors.toList());
        return Res.ok(list);
    }

    /**
     * 角色信息
     */
    @GetMapping("/info/{roleId}")
    @PreAuthorize("@pms.hasPermission('sys:role:info')")
    @ApiOperation(value = "角色信息详情")
    public Result<SysRole> info(@ApiParam(name = "角色id") @PathVariable("roleId") Long roleId) {
        SysRole role = sysRoleService.getById(roleId);
        if (StrUtil.isNotBlank(role.getDsScope())) {
            role.setDsScopeList(Arrays.asList(role.getDsScope().split(",")));

        }
        return Res.ok(role);
    }


    /**
     * 查询角色所对应的权限
     *
     * @param roleId
     * @return
     */
    @GetMapping("/info/menu/{roleId}")
    @ApiOperation(value = "查询角色对应权限信息")
    public Result<List<Long>> menuList(@ApiParam(name = "角色id") @PathVariable("roleId") Long roleId) {
        List<Long> collect = sysPermissionService.findMenuByRoleId(roleId)
                .stream().map(SysPermission::getId).collect(Collectors.toList());
        return Res.ok(collect);
    }


    /**
     * 删除原来权限  增加新菜单
     *
     * @param menuList
     * @return
     */
    @PostMapping("/info/menu/{roleId}")
//    @PreAuthorize("@pms.hasPermission('sys:role:updatePerm')")
    @ApiOperation(value = "给角色增加对应的权限")
    public Result saveMenu(@ApiParam(name = "权限列表") @RequestBody List<Long> menuList,
                           @ApiParam(name = "角色id") @PathVariable Long roleId) {
        sysRoleService.saveRoleMenu(menuList, roleId);
        return Res.ok("保存成功");
    }

    /**
     * 保存角色
     */
    @PostMapping("/save")
    @PreAuthorize("@pms.hasPermission('sys:role:save')")
    @ApiOperation(value = "增加一个角色")
    public Result<Boolean> save(@Valid @RequestBody SysRole role) {
        if (role.getDsScopeList() != null) {
            role.setDsScope(String.join(",", role.getDsScopeList()));
        }
        return Res.ok(sysRoleService.save(role));
    }

    /**
     * 修改角色
     */
    @PostMapping("/update")
    @PreAuthorize("@pms.hasPermission('sys:role:update')")
    @ApiOperation(value = "更新角色")
    public Result<Boolean> update(@Valid @RequestBody SysRole role) {
        if (role.getRoleId() == null) {
            throw new BizException("角色ID不能为空");
        }
        if (role.getDsScopeList() != null) {
            role.setDsScope(String.join(",", role.getDsScopeList()));
        }
        return Res.ok(sysRoleService.updateById(role));
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/delete/{roleId}")
    @PreAuthorize("@pms.hasPermission('sys:role:del')")
    @ApiOperation(value = "删除角色")
    public Result<Boolean> delete(@ApiParam(value = "角色id") @PathVariable("roleId") Long roleId) {
        return Res.ok(sysRoleService.removeRoleById(roleId));
    }

}

